import { _decorator, Component, Node } from 'cc';
import { WebSocketGameManager } from './WebSocketGameManager';
const { ccclass, property } = _decorator;

@ccclass('WebSocketClient')
export class WebSocketClient extends Component {
    static client: WebSocket = null;

    start() {
        this.connect();
        this.open();
        this.onmessage();
        // this.send();
    }

    private connect() {
        // TODO: 连接WebSocket服务器
        try {
            WebSocketClient.client = new WebSocket('ws://localhost:8080');
            console.log('WebSocket开始连接...');
        }
        catch (error) {
            console.error('WebSocket连接失败:', error);
        }
    }
    private open() {
        // TODO: 打开WebSocket连接
        WebSocketClient.client.onopen = () => {
            console.log('WebSocket连接已打开');
        };
    }
    /**
     * TODO: 接收WebSocket消息
     *  */
    private onmessage() {
        // TODO: 接收WebSocket消息
        WebSocketClient.client.onmessage = (event) => {
            // console.log('收到消息:', event.data);
            // TODO: 处理接收到的消息
            WebSocketGameManager.MessageEventHandler.emit("MessageUpdate", event.data);
        }
    }

    private close() {
        // TODO: 关闭WebSocket连接
        WebSocketClient.client.onclose = () => {
            console.log('WebSocket连接已关闭');
        };
    }

    public static send(message: string) {
        // TODO: 发送消息到WebSocket服务器
        WebSocketClient.client.send(message);
    }

    protected onDestroy(): void {
        this.close();
    }
}


